package com.example.java11_zklock.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.java11_zklock.doman.Goods;
import com.example.java11_zklock.mapper.GoodsMapper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private CuratorFramework curatorFramework;

//    @Override
//    public String buyGoods(Long goodsId,Long count) throws Exception {
//        //创建zk分布式锁
////        InterProcessMutex lock = new InterProcessMutex(curatorFramework,"/Locks");
//        try {
//            //上锁
////            lock.acquire();
//            Goods goods = goodsMapper.selectOne(new QueryWrapper<Goods>().lambda().eq(Goods::getGoodsId, goodsId));
////            Thread.sleep(new Random().nextInt(1000));
//            if (goods == null) {
//                return "商品不存在";
//            }
//            if (goods.getGoodsStock() < count) {
//                return "商品库存不足";
//            }
//            goods.setGoodsStock(goods.getGoodsStock() - count);
//            int num = goodsMapper.updateById(goods);
//            if (num > 0) {
//                return "购买成功";
//            }
//        }finally {
//            //释放锁
////            lock.release();
//        }
//        return "购买失败";
//    }

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public String buyGoods(Long goodsId,Long count) throws Exception {
        //创建锁
        RLock lock = redissonClient.getLock("goods_lock_" + goodsId);
        try {
            //第一个参数100s表示尝试获取分布式锁，并且最大的等待获取锁的时间为100s
            //第二个参数10s表示上锁之后，10s内操作完毕将自动释放锁
//            if(lock.tryLock(100, 10, TimeUnit.SECONDS)) {
                Goods goods = goodsMapper.selectOne(new QueryWrapper<Goods>().lambda().eq(Goods::getGoodsId, goodsId));
                Thread.sleep(new Random().nextInt(100));
                if (goods == null) {
                    return "商品不存在";
                }
                if (goods.getGoodsStock() < count) {
                    return "商品库存不足";
                }
                goods.setGoodsStock(goods.getGoodsStock() - count);
                int num = goodsMapper.updateById(goods);
                if (num > 0) {
                    return "购买成功";
                }
//            }
        }finally {
            //释放锁
//            lock.unlock();
        }
        return "购买失败";
    }
}
